package com.fengxu.springcloud.controller;

import com.fengxu.springcloud.entity.CommonResult;
import com.fengxu.springcloud.entity.Payment;
import com.fengxu.springcloud.service.PaymentService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Log4j2
@RequestMapping("/api/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/create")
    public CommonResult create(@RequestBody Payment payment){
        log.info("提供者"+serverPort+"payment -> " + payment);
       int res =  paymentService.execute(paymentMapper -> paymentMapper.insert(payment));
       if(res > 0){
           return new CommonResult(200,"插入成功,serverPort:"+serverPort,res);
       } else {
           return new CommonResult(404,"插入失败,serverPort:"+serverPort,null);
       }
    }

    @GetMapping("/find/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        log.info("提供者"+serverPort+" id -> " + id);
        Payment payment = paymentService.execute(paymentMapper -> paymentMapper.selectById(id));
        if(payment != null){
            return new CommonResult(200,"查询成功,serverPort"+serverPort,payment);
        } else {
            return new CommonResult(404,"未找到该编号的订单!,serverPort"+serverPort,null);
        }
    }

    @GetMapping("/zipkin")
    public String paymentZipkin(){
        return "welcome to use paymentZipkin";
    }

    @GetMapping("/timeout")
    public String feignTimeout(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Hello " + serverPort;
    }

    @GetMapping("/discovery")
    public Object discovery(){
        // 获取集群中有哪些微服务即微服务列表
        List<String> services = discoveryClient.getServices();
        Map<String,Object> map = new HashMap<>();
        map.put("services",services);
        // 根据微服务名称获取对应的微服务实例
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        map.put("instance",instances);
        return map;
    }

}
